<template>
  <div>
    <van-nav-bar title="登录" left-arrow></van-nav-bar>
    <van-cell-group>
      <van-field
        v-model="userInfo.mobile"
        required
        center
        clearable
        label="手机号"
        placeholder="请输入手机号"
        :error-message="errMsg.mobile"
      />
      <van-field
        v-model="userInfo.code"
        required
        center
        clearable
        label="验证码"
        placeholder="请输入验证码"
        :error-message="errMsg.code"
      >
        <template #button>
          <van-button size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <van-button @click="goLogin" class="login-btn" type="info" round block
      >提交</van-button
    >
  </div>
</template>
<script>
import { login } from "@/api/user.js";
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      userInfo: {
        mobile: "13912345678",
        code: "246810"
      },
      //错误提示
      errMsg: {
        mobile: "",
        code: ""
      }
    };
  },
  created() {
    console.log("路由获取", this.$route);
  },
  methods: {
    ...mapMutations(["setTokenInfo"]),
    //登录
    async goLogin() {
      //1.获取数据
      const userInfo = this.userInfo;
      //2.对数据进行非空验证
      if (!userInfo.mobile) {
        this.errMsg.mobile = "手机号不能为空";
        return;
      } else {
        this.errMsg.mobile = "";
      }
      if (!userInfo.code) {
        this.errMsg.code = "验证码不能为空";
        return;
      } else {
        this.errMsg.code = "";
      }
      //3.点击登录按钮展示 loading 防止重复点击
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "登录验证中...",
        mask: true // 整体添加一个遮罩
      });
      //4.发送请求
      try {
        const res = await login(userInfo);
        console.log(res);
        this.$toast.success("登录成功");
        this.setTokenInfo(res.data.data);
        // 用户跳转
        // 根据当前路由参数，决定跳到哪里去
        //在router index.js 中添加了全局路由守卫  如果想访问/user  需要先判断有没有token
        //没有token 就跳转到登录页  登录成功以后  就跳转到一开始请求的页面
        const backto = this.$route.query.backto || "/";
        console.log(backto);
        this.$router.push(backto);
        // this.$router.push({ path: "/" });
      } catch (error) {
        console.log(error);
        this.$toast.success("登录失败");
      }
    }
  }
};
</script>
<style lang="less">
#app {
  .login-btn {
    width: 320px;
    margin: 20px auto;
  }
}
</style>
